package com.yzs.exam.config.spring.security;

import com.yzs.exam.common.base.SystemCode;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录未授权统一管理
 * @author yzs
 * @create 2021-03-21 3:32
 */
@Component
public class LoginAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

    private final Logger logger = LoggerFactory.getLogger(LoginAuthenticationEntryPoint.class);
    /**
     * 指定登录URL
     */
    public LoginAuthenticationEntryPoint() {
        super("/api/user/login");
    }

    /**
     * 未登录抛出未授权的的响应
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        logger.info(request.getRemoteHost() + "用户未登录授权");
        RestUtil.response(response, SystemCode.UNAUTHORIZED);
    }
}
